package com.lin.gulimall.order.listener;


import com.alipay.api.AlipayApiException;
import com.lin.gulimall.order.constant.PaymentConstant;
import com.lin.gulimall.order.service.OrderService;
import com.lin.gulimall.order.service.impl.AliPayServiceImpl;
import com.lin.gulimall.order.service.impl.PayContextStrategy;
import com.lin.gulimall.order.vo.AliPayAsyncVO;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * 订单支付成功监听器
 *
 */
public class OrderPayedListener {

    @Autowired
    PayContextStrategy payContextStrategy;
    @Autowired
    AliPayServiceImpl aliPayService;
    @Autowired
    OrderService orderService;


    /**
     * 支付宝支付异步通知
     * 只有支付成功会触发
     *
     * @param request
     * @param asyncVo
     */
    @PostMapping(value = "/payed/ali/notify")
    public String handleAliNotify(HttpServletRequest request, AliPayAsyncVO asyncVo) throws AlipayApiException, UnsupportedEncodingException {
        asyncVo.setPayCode(PaymentConstant.PayType.ALI_PAY.getCode()); // 封装付款类型
        // 验签
        Boolean signVerified = aliPayService.verify(request);
        if (signVerified) {
            // 修改订单状态
            System.out.println("签名验证成功...修改订单状态");
            String result = aliPayService.handlePayResult(asyncVo);
            return result; // 返回success，支付宝将不再异步回调 而且success能退款 finish不行
        } else {
            System.out.println("签名验证失败...");
            return "error";
        }
    }

    /**
    微信异步回调
     */
    @PostMapping(value = "/pay/notify")
    public String asyncNotify(@RequestBody String notifyData) {
        //异步通知结果
        return orderService.asyncNotify(notifyData);
    }
}
